package org.s170.servlet.WebServlet;

import com.google.gson.Gson;
import org.s170.vo.ImageVo;
import org.s170.vo.WangVo;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/api/wangImg.do")
@MultipartConfig
public class WangImgServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //获取跨域时请求方式,如果是options请求,那就放行
        String method = req.getMethod();
        if("options".equalsIgnoreCase(method)) {
            return ;
        }

        System.out.println("upload...");

        Part part = req.getPart("attach") ;

        // 获取项目的真实的物理路径
        String path = req.getServletContext().getRealPath("/") + "file/" ;

        // 获取请求内容
        String header = part.getHeader("Content-Disposition") ;
        String realName = header.substring(header.indexOf("filename=")+10,header.length()-1);

        part.write(path + realName) ;

        //调用方法获取服务器文件夹的路径
        String basePath = getServerPath(req,"file");

        ImageVo imageVo = new ImageVo();
        imageVo.setAlt("aa");
        imageVo.setHref(basePath +"/"+realName);
        imageVo.setUrl(basePath +"/"+realName);

        WangVo wangVo = new WangVo();
        List<ImageVo> list = new ArrayList<>() ;
        list.add(imageVo) ;
        wangVo.setData(list);
        wangVo.setErrno(0);

        String json = new Gson().toJson(wangVo);

        PrintWriter out = resp.getWriter();

        out.print(json);

        out.flush();
        out.close();
    }


    private String getServerPath(HttpServletRequest req,String dir) {
        // 协议：http
        String scheme = req.getScheme();

        // 服务地址 : localhost
        String serverName = req.getServerName();

        // 端口号:8080
        int port = req.getServerPort();

        // 上下文路径: wang/   war包的名字
        String contextPath = req.getContextPath();

        // http://localhost:8080/wang/file
        String basePath = scheme + "://" + serverName + ":" + port + contextPath + "/" +dir;

        return basePath;
    }
}
